<template>
    <SCDialog
        v-model="visible"
        title="修改密码"
        :width="360"
        :before-close="handleBeforClose"
        @close="handleBeforClose"
    >
        <SCForm
            class="form"
            :model="form"
            label-width="124px"
            label-position="top"
            ref="formRef"
            :rules="rules"
        >
            <SCForm-item prop="originalPwd" label="原始密码">
                <SCInput
                    v-model="form.originalPwd"
                    type="password"
                    show-password
                    placeholder="请输入"
                    clearable
                />
            </SCForm-item>
            <SCForm-item prop="newPwd" label="设置密码（长度为9~16个字符）" required>
                <SCInput
                    v-model="form.newPwd"
                    type="password"
                    show-password
                    placeholder="请输入"
                    clearable
                />
            </SCForm-item>
            <SCForm-item prop="newPwdConfirm" label="确认密码" required>
                <SCInput
                    v-model="form.newPwdConfirm"
                    type="password"
                    show-password
                    placeholder="请输入"
                    clearable
                />
            </SCForm-item>
        </SCForm>
        <template #footer>
            <span class="dialog-footer">
                <SCButton class="mr10" @click="emits('update:modelValue', false)">取消</SCButton>
                <SCButton type="primary" @click="onSubmit" :loading="submitLoading">确定</SCButton>
            </span>
        </template>
    </SCDialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { updatePassword } from "../api/userManager";
import md5 from "md5";
import { SCMessage } from "@sribd/sc-ui/lib";
import { useRouter } from "vue-router";

const props = defineProps(["modelValue"]);
const emits = defineEmits(["update:modelValue"]);
const router = useRouter();
const visible = ref(props.modelValue || false);
const form = reactive({
    originalPwd: "",
    newPwd: "",
    newPwdConfirm: "",
});
const formRef = ref();
const submitLoading = ref(false);

watch(
    () => props.modelValue,
    (val) => {
        visible.value = val;
    },
    {
        immediate: true,
    },
);

const passwordValidator = (rule: any, value: any, callback) => {
    if (!value) {
        return callback(new Error("请输入新密码"));
    } else if (value.length < 9 || value.length > 16) {
        formRef.value.clearValidate("newPwdConfirm");
        return callback(new Error("密码长度为9~16个字符"));
    } else if (form.newPwdConfirm) {
        formRef.value.validateField("newPwdConfirm");
    }
    return callback();
};

const confirmValidator = (rule: any, value: any, callback) => {
    if (!form.newPwd) {
        return callback(new Error("请先输入新密码"));
    } else if (!value) {
        return callback(new Error("请输入确认密码"));
    } else if (value !== form.newPwd) {
        return callback(new Error("两次密码不一致"));
    } else return callback();
};

const rules = {
    originalPwd: [
        {
            required: true,
            message: "请输入原始密码",
            trigger: ["change"],
        },
    ],
    newPwd: [
        {
            validator: passwordValidator,
            trigger: ["change"],
        },
        {
            required: true,
            message: "请输入新密码",
            trigger: ["change"],
        },
    ],
    newPwdConfirm: [
        {
            validator: confirmValidator,
            trigger: ["change"],
        },
        {
            required: true,
            message: "请输入确认密码",
            trigger: ["change"],
        },
    ],
};

const onSubmit = async () => {
    const valid = await formRef.value.validate();
    if (!valid) return;
    const params = {
        originalPwd: md5(form.originalPwd) as string,
        newPwd: md5(form.newPwd) as string,
    };
    submitLoading.value = true;
    try {
        await updatePassword(params);
        SCMessage({ message: "修改成功,请重新登录", type: "success" });
        emits("update:modelValue", false);
        router.push("/login");
    } catch (error) {
        SCMessage({ message: error.msg || "修改失败", type: "error" });
    } finally {
        submitLoading.value = false;
    }
};

const handleBeforClose = (done: any) => {
    form.originalPwd = "";
    form.newPwd = "";
    form.newPwdConfirm = "";
    setTimeout(async () => {
        await formRef.value.clearValidate();
        emits("update:modelValue", false);
        done && done();
    }, 0);
};
</script>

<style lang="scss" scoped>
:deep(.form) {
    display: flex;
    flex-direction: column;
    .sc-input {
        width: 100%;
    }
}
:deep(.el-dialog__header) {
    text-align: initial;
}
</style>
